package com.linkstec.concurrent;

import java.time.LocalDateTime;

/**
 * @author ：mmzsblog
 * @description：共享变量在线程间的可见性测试
 */
public class VisibilityDemo {

    // 状态标识flag
    private static volatile boolean flag = true;

    public static void main(String[] args) throws InterruptedException {
        System.out.println(LocalDateTime.now() + "主线程启动计数子线程");
        new CountThread().start();

        Thread.sleep(3000);
        // 设置flag为false，使上面启动的子线程跳出while循环，结束运行
        VisibilityDemo.flag = false;
        System.out.println(LocalDateTime.now() + "主线程将状态标识flag被置为false了");
    }

    static class CountThread extends Thread {
        @Override
        public void run() {
            System.out.println(LocalDateTime.now() + "计数子线程start计数");
            int i = 0;
            while (VisibilityDemo.flag) {
                i++;
            }
            System.out.println(LocalDateTime.now() + "计数子线程end计数，运行结束：i的值是" + i);
        }
    }

}